import axios from 'axios'
import { message } from 'antd';
import { ResData, AxiosResponense } from './requet_config'
import { getToken } from '@/util'
import eventBus from '@/util/event'


const axiosInstance = axios.create({
    baseURL: '/api',
    timeout: 2000,
    headers: { 'X-Custom-Header': 'foobar' }
});

/**
 * 请求拦截
 */
axiosInstance.interceptors.request.use(
    config => {
        config.headers['token'] = getToken() || ''
        // 防止缓存，GET请求默认带_t参数
        return config
    },
    error => {
        return Promise.reject(error)
    }
)
/**
 * 登录拦截
 */
axiosInstance.interceptors.response.use(
    (response) => {
        // 请求成功，直接返回response
        if (response.data.code !== 0) {
            ErrorHandling(response.data.code, response.data.msg)
            return Promise.reject(response.data)
            return response.data
        }
        return response.data;
    },
    error => {
        ErrorHandling(error.response.status)
        return Promise.reject(error);
    }
);
const ErrorHandling = (code: number, msg: string = '') => {
    switch (code) {
        case 401:
            eventBus.emit('login-again')
            message.error('请重新登录')
            break;
        default:
            message.error(msg)
            break;
    }
}
export default axiosInstance;